package com.tueye.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tueye.base.util.Page;
import com.tueye.entity.Adsite;
import com.tueye.service.IAdsiteService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.UUIDGenerator;

/**
 * 用户添加控制层操作demo
 * spring mvc 2.5 支持MultiActionController
 * @author hanxiaowei
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/adsite.do")
public class AdsiteController extends BaseController {
	private Log log = LogFactory.getLog(AdsiteController.class);
	
	@Autowired
	@Qualifier("adsiteService")
	private IAdsiteService adsiteService;
	
	//@RequestMapping(method = { RequestMethod.POST })
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query)
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.Adsite ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		if(StringUtils.isNotEmpty(query)) hql.append(" where "+qtype+" ='"+query+"'");
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		Page pageModel = adsiteService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		//生成json字符串
//		if(pageModel.getResult() instanceof ArrayList){
//			System.out.println("*******"+pageModel.getResult());
//			
//		}
		String jsonStr = getJsonString((ArrayList)pageModel.getResult(),pageInfo);
		
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
/*		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.getWriter().write(jsonStr);
		response.getWriter().flush();
		response.getWriter().close();*/
		
		return null;
	}
	
	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String adsite_name = (String)request.getParameter("adsite_name");
		String adsite_description = request.getParameter("adsite_description");
		String moduleId = request.getParameter("moduleId");
		String moduleName = request.getParameter("moduleName");
		String modulePlate = request.getParameter("modulePlate");
		//新增
		if(mainId.length()==0){
		Adsite adsite = new Adsite();
		adsite.setId(new UUIDGenerator().getUUID());
		adsite.setAdsite_name(adsite_name);
		adsite.setAdsite_description(adsite_description);
		adsite.setModuleId(moduleId);
		adsite.setModuleName(moduleName);
		adsite.setModulePlate(modulePlate);
		adsite.setSys_time(new Date());
		adsiteService.addAdsite(adsite);
		}else{
			//修改
			Adsite adsite = new Adsite();
			adsite = adsiteService.getAdsiteById(mainId);
			adsite.setAdsite_name(adsite_name);
			adsite.setAdsite_description(adsite_description);
			adsite.setModuleId(moduleId);
			adsite.setModuleName(moduleName);
			adsite.setModulePlate(modulePlate);
			adsite.setSys_time(new Date());
			adsiteService.addAdsite(adsite);
		}
		
		return null;
	}
	
	/**
	 传递修改数据
	 */

	@RequestMapping(params = "action=edit")
	public String edite(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		Adsite adsite = new Adsite();
		//修改
	    adsite = adsiteService.getAdsiteById(mainId);
	    request.setAttribute("adsite", adsite);
	    return "/pages/admin/ad/addAdsite";
	}
	
	@RequestMapping(params = "action=delete")
	public void delete (HttpServletRequest request, HttpServletResponse response){
		
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			adsiteService.delAdsite(id);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
		
	}
	
	
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			Adsite adsite = (Adsite) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
			cellMap.put("adinfos", "<a href='adinfos.jsp?id="+adsite.getId()+"'>查看</a>");
    		cellMap.put("cell", new Object[]{
    				
    				adsite.getId(),
    				i+1,
    				adsite.getAdsite_name(),
    				adsite.getAdsite_description(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",adsite.getSys_time()),
    				"<a href='adinfos.jsp?id="+adsite.getId()+"'>查看</a>"
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		//log.info("############# "+json);
		return json;
	}
	
}
